package top.yuhaitao.core.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yuhaitao.core.model.CityModel;
import top.yuhaitao.core.mybatis.dbo.TCity;
import top.yuhaitao.core.mybatis.dbo.TCityExample;
import top.yuhaitao.core.mybatis.mapper.TCityMapper;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * city
 *
 * @author ht.yu
 */

@RestController
@RequestMapping("/city")
public class CityController {

    private final static String CITYCONTROLLER_CITY = "CityController-city";

    @Resource
    private TCityMapper tCityMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据城市名称获取城市列表
     *
     * @return
     */
    @RequestMapping("/getCityListByCityName")
    public Map<String, Object> getCityListByCityName() {

        String cityJsonList = stringRedisTemplate.opsForValue().get(CITYCONTROLLER_CITY);
        if (StringUtils.isEmpty(cityJsonList)) {
            List<TCity> tCities = tCityMapper.selectByExample(new TCityExample());
            cityJsonList = new Gson().toJson(tCities);
            stringRedisTemplate.opsForValue().set(CITYCONTROLLER_CITY, cityJsonList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("retCode", "0000");
        map.put("success", true);
        map.put("retMsg", "执行成功");
        map.put("data", new Gson().fromJson(cityJsonList, new TypeToken<List<CityModel>>() {
        }.getType()));
        return map;
    }

}
